package com.xfcy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xfcy.base.exeption.XfcyException;
import com.xfcy.content.mapper.TeachplanMapper;
import com.xfcy.content.mapper.TeachplanMediaMapper;
import com.xfcy.content.model.dto.BindTeachplanMediaDto;
import com.xfcy.content.model.dto.SaveTeachplanDto;
import com.xfcy.content.model.dto.TeachplanDto;
import com.xfcy.content.model.po.Teachplan;
import com.xfcy.content.model.po.TeachplanMedia;
import com.xfcy.content.service.TeachplanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author 晓风残月Lx
 * @date 2023/6/15 23:06
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Resource
    TeachplanMapper teachplanMapper;

    @Resource
    TeachplanMediaMapper teachplanMediaMapper;

    /**
     * 根据课程id查询课程计划
     * @param courseId 课程id
     * @return
     */
    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**
     * 新增、修改、保存课程计划
     * @param saveTeachplanDto
     */
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        // 通过课程计划的id判断是新增还是修改
        Long teachplanId = saveTeachplanDto.getId();
        if (teachplanId == null) {
            // 新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);

            int teachplanCount = getTeachplanCount(saveTeachplanDto.getCourseId(), saveTeachplanDto.getParentid());
            teachplan.setOrderby(teachplanCount + 1);

            teachplanMapper.insert(teachplan);
        } else {
            // 修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);

        }
    }

    /**
     * 课程上移或下移
     * @param teachplanId
     * @param moveType
     */
    @Transactional
    @Override
    public void teachplanMove(Long teachplanId, String moveType) {
        Teachplan teachplan = checkTeachplanById(teachplanId);

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getParentid()).eq(Teachplan::getCourseId, teachplan.getCourseId());

        switch (moveType) {
            case "movedown":
                queryWrapper.ge(Teachplan::getOrderby, teachplan.getOrderby());
                queryWrapper.orderByAsc(Teachplan::getOrderby);
                break;
            case "moveup":
                queryWrapper.le(Teachplan::getOrderby, teachplan.getOrderby());
                queryWrapper.orderByDesc(Teachplan::getOrderby);
                break;
            default:
                 XfcyException.cast("不支持的类型");
        }

        queryWrapper.last("limit 2");

        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        if (teachplans.size() != 2) {
            throw new XfcyException("当前计划无法移动");
        }
        Integer temp = teachplans.get(0).getOrderby();
        teachplans.get(0).setOrderby(teachplans.get(1).getOrderby());
        teachplans.get(1).setOrderby(temp);

        teachplanMapper.updateById(teachplans.get(0));
        teachplanMapper.updateById(teachplans.get(1));

    }

    /**
     * 删除课程计划 分为大章节和小章节
     * @param id
     */
    @Transactional
    @Override
    public void delete(Long id) {

        if (id == null) {
            //传入参数为空抛出异常
            throw  new XfcyException("id不能不为空");
        }

        // 查出课程计划
        Teachplan teachplan = teachplanMapper.selectById(id);
        // 大章节和小章节
        if (teachplan.getGrade() == 0) {
            Integer count = teachplanMapper.selectCount(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getParentid, teachplan.getParentid()));
            if (count > 0) {
                throw  new XfcyException("课程计划信息还有子级信息，无法操作");
            }
            // 查出所有比删除章节大的排序都减1
            List<Teachplan> teachplanList = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, teachplan.getCourseId()).gt(Teachplan::getOrderby, teachplan.getOrderby()).orderByAsc());
            teachplanList.forEach(item -> {
                item.setOrderby(item.getOrderby() - 1);
                teachplanMapper.updateById(item);
            });
            // 删除章节
            teachplanMapper.deleteById(id);
        } else {
            // 小章节
            teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, id));

            // 查出所有比删除章节大的排序都减1
            List<Teachplan> teachplanList = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getParentid()).gt(Teachplan::getOrderby, teachplan.getOrderby()).orderByAsc());
            teachplanList.forEach(item -> {
                item.setOrderby(item.getOrderby() - 1);
                teachplanMapper.updateById(item);
            });
            // 删除章节
            teachplanMapper.deleteById(id);
        }

    }

    /**
     * 绑定媒资
     * @param bindTeachplanMediaDto
     * @return
     */
    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {

        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XfcyException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XfcyException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        // 先删除原有记录，根据课程计划id删除它所绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId()));

        // 添加原有记录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto, teachplanMedia);
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    /**
     * 删除媒资
     * @param teachplanId
     * @param mediaId
     */
    @Override
    public void deleteAssociation(Long teachplanId, Long mediaId) {
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, teachplanId).eq(TeachplanMedia::getMediaId, mediaId));
    }

    private Teachplan checkTeachplanById(Long teachplanId) {
        return Optional.ofNullable(teachplanMapper.selectById(teachplanId)).orElseThrow(() ->  new XfcyException("教学计划不存在"));
    }


    private int getTeachplanCount(Long courseId, Long parentId) {
        // 确定排序字段，找到它的网络节点个数，排序个数就是个数加1
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }



}
